<template>
  <BaseMainSlot>
    <template v-slot:btnsBar>
      <ActionBar :page-no="78" :save-active="true" :has-edit="false" :has-save="true" :has-del="false" :has-add="false"
        @save="save('ruleForm')" />
      <!-- @qrShow="qrShow" -->
    </template>
    <template v-slot:categoryBox>
      <CategoryBar :categoryList="categoryList" @categoryBar="categorySearch" />
    </template>
    <template v-slot:content>
      <el-form ref="ruleForm" :model="formData" :rules="rules" class="el-form">
        <el-row :gutter="15">
          <el-col :span="7">
            <el-form-item label="码单号： " props="recordCodeObj" class="w100p">
              <el-select filterable clearable v-model="formData.recordCodeObj" @change="recordCodeChange" value-key="checkRecordId"
                allow-create filterable clearable>
                <el-option v-for="(item, index) in recordList" :key="index + 'recordCode'" :label="item.recordCode"
                  :value="item" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="7">
            <el-form-item label="检验范畴： " class="w100p">
              <el-select filterable clearable v-model="checkType" multiple @change="handleTableData" filterable clearable>
                <el-option v-for="(item, index) in tempCheckType" :key="index + 'tempCheckType'"
                  :label="item.categoryTypeStr" :value="item.categoryType" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="供应商： " class="w100p">
              <el-input v-model="formData.a" clearable placeholder />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="入塘塘号： " class="w100p">
              <el-select filterable clearable v-model="formData.fishPondId" filterable clearable>
                <el-option v-for="(item, index) in fishPondList" :key="index + 'fishPond'" :label="item.pondName"
                  :value="item.fishPondId" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col :span="5">
            <el-form-item label="入塘批次： " class="w100p">
              <el-select filterable clearable v-model="formData.productionBatchId" @change="querySpecByBatch" filterable clearable>
                <el-option v-for="(item, index) in batchList" :key="index + 'productionBatchId'"
                  :label="`${item.mnecode}_${item.varietyName}`" :value="item.productionBatchId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="9">
            <el-form-item label="规格比例： " class="w100p">
              <div v-for="(item, index) in specificationList" :key="index">
                <!-- <span></span> -->
                <el-input v-model="specificationList[index].proportion" clearable placeholder
                  style="width:150px;margin-right:10px;">
                  <template slot="prepend">{{ item.specificationName }}</template>
                </el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="总量： " class="w100p">
              <el-input v-model="formData.checkTotalWeight" clearable placeholder />
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="条数： " class="w100p">
              <el-input v-model="formData.checkNum" clearable placeholder />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table ref="tableData" :data="tableData" border :span-method="objectSpanMethod" style="width:100%">
        <el-table-column label="检验范畴" width="200" prop="categoryType" :show-overflow-tooltip="true" align="center">
          <template slot-scope="scope">
            <div style="width:160px !important"
              :style="'height:' + scope.row.categoryTypecount * 40 + 'px;line-height:' + scope.row.categoryTypecount * 40 + 'px'">
              {{ scope.row.categoryTypeStr }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="checkSubject" width="120" label="检验科目" align="center" :show-overflow-tooltip="true" />
        <el-table-column prop="checkStandard" label="检验标准" align="left" min-width="200" :show-overflow-tooltip="true" />
        <el-table-column prop="result" align="center" :show-overflow-tooltip="true" label="检验结果">
          <template slot-scope="scope">
            <el-input v-if="scope.row.answerType === 'TEXTTYPE'" v-model="tableData[scope.$index].checkResult" clearable
              @change="tableData[scope.$index].whetherResult = true" />
            <el-radio-group v-if="scope.row.answerType === 'TWOTERMSTYPE'" v-model="tableData[scope.$index].checkResult"
              @change="radioChange(scope.$index)">
              <el-radio v-for="(item, index) in scope.row.enumContentList" :key="index + 'specification'" :label="item">{{
                item }}</el-radio>
            </el-radio-group>
            <el-input v-if="scope.row.answerType === 'NUMTYPE'" v-model="tableData[scope.$index].checkResult"
              type="number" clearable @change="setfinallyScoremet(scope.$index)" />
          </template>
        </el-table-column>
        <el-table-column :show-overflow-tooltip="true" align="center" prop="finallyScore" label="检验结果是否合格">
          <template slot-scope="scope" v-if="tableData[scope.$index].checkResult">
            <!-- {{ tableData[scope.$index].whetherResult }} -->
            <div v-if="scope.row.answerType === 'TEXTTYPE'">合格</div>
            <div v-if="scope.row.answerType === 'TWOTERMSTYPE' || scope.row.answerType === 'LISTTYPE'">
              {{ tableData[scope.$index].checkResult === tableData[scope.$index].standardValue ? '合格' : '不合格' }}</div>
          </template>
        </el-table-column>
      </el-table>
      <el-form :model="formData" class="el-form">
        <el-row style="display:flex;justify-content: flex-end;flex-wrap: nowrap;">
          <el-col :span="4">
            <el-form-item label="检验日期： " class="w100p">
              <el-date-picker v-model="checkRecordStaffMapperList[0].checkTime" value-format="yyyy-MM-dd HH:mm:ss"
                type="datetime" placeholder="选择日期时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="检验人： " class="w100p">
              <el-select filterable clearable v-model="staffObj" @change="staffChange" value-key="staffId" allow-create filterable clearable>
                <el-option v-for="(item, index) in staffList" :key="index + 'staffList'" :label="item.staffName"
                  :value="{ staffId: item.staffId, staffName: item.staffName }" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </template>
  </BaseMainSlot>
</template>

<script>
import ActionBar from "@/components/ActionBar";
import BaseMainSlot from "@/components/BaseMainSlot/kong-new.vue";
import CategoryBar from "@/components/CategoryBar/index.vue";
import { mymixin } from "@/utils/mixins";
import { mapGetters } from "vuex";

import verifyApi from "@/api/inspection-management/verify-configuration";
import InspectionRecordApi from "@/api/inspection-management/inspection-record";
import DetectionTypeApi from "@/api/inspection-management/detection-type-management";
import BatchMangeApi from "@/api/batch-mange";
import FishPondApi from "@/api/basic-info-manage/fishPond";
import SpecificationApi from "@/api/basic-info-manage/specification";
import StaffApi from "@/api/basic-info-manage/staff";
export default {
  name: "HistoryInputPondRecord",
  components: {
    ActionBar,
    BaseMainSlot,
    CategoryBar
  },
  mixins: [mymixin],
  data () {
    return {
      mnecode: "", //批次编号
      purchaseOrderId: "", //采购订单编号
      fishPondId: "", //养殖鱼塘ID
      fishVarietyId: "", //养殖品种ID
      staffObj: {},
      inputDate: "", //检验日期
      checkedIdList: [],
      recordList: [], //全部未完成检验记录
      fishPondList: [], //全部鱼塘
      specificationList: [], //全部规格
      checkRecordStaffMapperList: [{}], //检验范畴及检验人列表
      batchList: [], //批次
      FishVarietyData: [], //全部品种
      staffList: [], //全部员工
      activeName: "",
      categoryList: [],
      originalCheckConfigDetailList: [],//用于存储初步处理后的原始数据
      tempList: [],//用于存储处理后的检验配置数据
      tempCheckType: [],//用于存储检验配置的检验范畴
      checkType: [],//当前选中的检验范畴
      checkTime: undefined,//检验时间
      rules: {
        recordCodeObj: [
          { required: true, message: "请输入批次编号", trigger: ["change", "blur"] }
        ],
        pondRatio: [
          { required: true, message: "请输入批次鱼塘占比", trigger: ["change", "blur"] }
        ],
        fishPondId: [
          { required: true, message: "请选择批次所在鱼塘", trigger: ["change", "blur"] }
        ],
        fishVarietyId: [
          { required: true, message: "请选择养殖品种", trigger: ["change", "blur"] }
        ],
        breedType: [
          { required: true, message: "请选择养殖方式", trigger: ["change", "blur"] }
        ],
        clearCompleteFlag: [
          { required: true, message: "请选择批次完成方式", trigger: ["change", "blur"] },
        ],
      },
    };
  },
  computed: {
    ...mapGetters({
      judgePermission: "permission/judgePermission"
    })
  },
  watch: {},
  created () {
    this.queryDetectionType();
    this.queryInspectionRecord();
    this.queryFishPond();
    this.queryStaff();
    this.queryBatch();
  },
  mounted () {
    // this.formData.checkStaffId = sessionStorage.getItem('staffId')
  },
  methods: {
    recordCodeChange (e) {
      this.formData = { ...e }
    },
    categorySearch (item) {
      this.formData.checkTypeId = item.checkTypeId;
      verifyApi.queryInfoByCheckTypeId({ checkTypeId: item.checkTypeId }).then(res => {
        this.formData.checkConfigId = res.checkConfigId
        this.originalCheckConfigDetailList = res.data.checkConfigDetailList
        this.listHandle(this.originalCheckConfigDetailList)
        this.handleConfigData(res.data.checkConfigDetailList);
      });
    },
    radioChange (index) {
      this.$set(this.tableData[index], 'whetherResult', this.tableData[index].checkResult === this.tableData[index].standardValue)
    },
    // 处理检验配置数据结构
    handleConfigData (configData) {
      this.tempList = [];
      this.tempCheckType = [];
      configData.forEach((item, index) => {
        if (this.tempCheckType.findIndex(item2 => item.categoryType === item2.categoryType) === -1) {
          this.tempCheckType.push({ categoryType: item.categoryType, categoryTypeStr: item.categoryTypeStr });
          this.tempList.push({ categoryType: item.categoryType, checkConfigDetailList: [] });
        }
      });
      configData.forEach((item, index) => {
        item.enumContentList = item.enumContent.split(",");
        let tempIndex = this.tempList.findIndex((item2, index2) => item.categoryType === item2.categoryType)
        this.tempList[tempIndex].checkConfigDetailList.push(item);
      });
      // console.log(this.tempList);
      // console.log(this.tempCheckType);
    },
    handleTableData (e) {
      this.checkRecordStaffMapperList[0].categoryTypeList = this.checkType
      this.tableData = []
      this.originalCheckConfigDetailList.forEach((item, index) => {
        if (this.checkType.findIndex((item2) => item2 === item.categoryType) !== -1) {
          this.tableData.push(item)
        }
      })
    },
    //查询检验类型
    queryDetectionType () {
      DetectionTypeApi.queryByCondition({}).then(res => {
        if (res.success === true) {
          const tempList = res.data;
          this.categoryList = [];
          tempList.forEach((item, index) => {
            tempList[index].id = index;
            tempList[index].name = item.checkTypeName;
          });
          this.$nextTick(function () {
            this.categoryList = tempList;
          });
        }
      });
    },
    // 查询未完成检验记录
    queryInspectionRecord () {
      InspectionRecordApi.queryByCondition({}).then(res => {
        this.recordList = res.data;
      });
    },
    //查询可选鱼塘
    queryFishPond () {
      FishPondApi.queryByCondition().then(res => {
        this.fishPondList = res.data;
      });
    },
    // 查询鱼塘下的批次
    queryBatch (e) {
      // BatchMangeApi.queryByCondition({status:"UN_COMPLETE"}).then(res => {
      BatchMangeApi.queryByCondition({}).then(res => {
        this.batchList = res.data;
      });
    },
    querySpecByBatch (e) {
      this.batchList.find((item) => {
        if (item.productionBatchId === e) {
          this.formData.productionBatchId = item.productionBatchId;
          SpecificationApi.queryByCondition({ fishVarietyId: item.fishVarietyId }).then(res => {
            this.specificationList = res.data;
          });
          return true
        }
      })
      // this.formData.productionBatchId = item.productionBatchId;
    },
    // 查询员工
    queryStaff () {
      StaffApi.queryByCondition().then(res => {
        this.staffList = res.data
      })
    },
    staffChange (e) {
      this.checkRecordStaffMapperList[0].staffId = e.staffId
      this.checkRecordStaffMapperList[0].staffName = e.staffName
    },
    // 输入评分时触发方法
    setfinallyScoremet (i) {
      var setconuntindex = this.tableList[i].checkSubjectIdcount + i;
      var newi = i;
      for (newi; newi < setconuntindex; newi++) {
        this.tableList[newi].checkResult = this.tableList[i].finallyScore;
      }
    },
    // -----单元合并处理相关-------
    // 合并单元格（此方法需要结合this.$listHandle(res.data.dat.list)处理过的数据）
    objectSpanMethod ({ row, column, rowIndex, columnIndex }) {
      // 找到第一列
      if (columnIndex === 0) {
        // 如果合并的个数大于1的话
        if (row.categoryTypecount >= 1) {
          return {
            rowspan: row.categoryTypecount,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      }
    },
    // 转化下请求回来的数据
    listHandle (list) {
      for (var key in list[0]) {
        var k = 0;
        var j = 0;
        while (k < list.length) {
          // list[k].checkResult = ''
          list[k][key + "count"] = 1;
          list[k][key + "number"] = j;
          for (var i = k + 1; i <= list.length - 1; i++) {
            if (list[k][key] === list[i][key] && list[k][key] !== "") {
              list[k][key + "count"]++;
              list[i][key + "count"] = 0;
              list[i][key + "number"] = j;
            } else {
              break;
            }
          }
          j++;
          k = i;
        }
      }
      return list;
    },
    save (formData) {
      this.$refs[formData].validate(async valid => {
        this.formData.checkRecordInfoList = this.tableData;
        this.formData.checkRecordSpecificationMapperList = this.specificationList;
        this.formData.checkRecordStaffMapperList = this.checkRecordStaffMapperList;
        await delete this.formData.batchObj
        console.log(this.formData);
        InspectionRecordApi.add(this.formData).then(res => {
          if (res.success) {
            this.formData = {};
            this.$message.success(res.message || "新增成功！");
          } else {
            this.$message.error(res.message || "新增失败！");
          }
        });
      });
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-input-group__prepend {
  background-color: #c9e9ff;
  padding: 5px;
}

// 单元格样式
::v-deep .el-table {
  position: relative;
}

::v-deep .el-table__body {
  height: auto !important;
}

::v-deep {
  .common-layout {
    height: calc(100% - 140px) !important;

    .content {
      overflow: auto;
    }
  }
}

.text_ellipsis {
  white-space: pre-wrap;
  width: 80px;
  display: flex;
  flex-wrap: wrap;
  overflow: auto;
  text-align: center;
  justify-content: center;
  align-items: center;
}

::v-deep .el-table .hang {
  background: #970b84;
  font-weight: bold;
  //   color:#bd1a1a;
}

.blue {
  //   background: #0cc415;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  text-align: center;
}

.white {
  //   background: #bd1a1a;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
  padding: 0 10px;
  text-align: center;
}

// 表格hover及选中样式
::v-deep .el-table tr:hover,
::v-deep .el-table--enable-row-hover .el-table__body tr:hover>td,
::v-deep .el-table--striped .el-table__body tr.el-table__row--striped.current-row td,
::v-deep .el-table__body tr.current-row>td {
  background-color: #15a0ca00 !important;
}

// el-form
::v-deep .el-form {
  display: flex;
  flex-wrap: wrap;
  padding: 2px;
  width: 100%;

  .el-form-item__label {
    color: #000;
    white-space: nowrap;
    font-size: 14px;
    min-width: 80px;
    text-align: end;
  }
}

::v-deep .el-form-item--medium {
  display: flex;
  margin-bottom: 0;
  padding: 10px;

  .el-form-item__content {
    display: flex;
    align-items: center;
    width: 100%;
    line-height: 36px;

    >span {
      white-space: nowrap;
      min-width: 50px;
      text-align: end;

      color: #000;
    }

    .el-input {
      width: 100%;
    }
  }

  .el-form-item__label {
    line-height: 36px;
  }
}

::v-deep {
  .el-row {
    width: 100%;
    border: #000 1px solid;
    border-bottom-width: 0;

    &:last-child {
      border-bottom-width: 1px;
    }

    .el-col {
      border: #000 1px solid;
      border-bottom-width: 0;
      border-right-width: 0;
      border-top-width: 0;

      &:first-child {
        border-left-width: 0;
      }
    }
  }
}
</style>
